package org.bigjava.novelplatform.service.impl;

import org.bigjava.novelplatform.common.enums.ContinuedState;
import org.bigjava.novelplatform.common.exception.ExceptionCodeMessage;
import org.bigjava.novelplatform.common.exception.UserActionException;
import org.bigjava.novelplatform.entity.Books;
import org.bigjava.novelplatform.entity.Writer;
import org.bigjava.novelplatform.mapper.BooksMapper;
import org.bigjava.novelplatform.mapper.UsersMapper;
import org.bigjava.novelplatform.mapper.WriterMapper;
import org.bigjava.novelplatform.service.AuthorBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

import static org.bigjava.novelplatform.common.constant.ComplexConstant.RESOURCE_PATH;

/**
 * 作者权限操作-管理书籍
 */
@Service
public class AuthorBookServiceImpl implements AuthorBookService {

    @Resource
    private BooksMapper booksMapper;

    @Resource
    private WriterMapper writerMapper;

    /**
     * 发布书籍 参数:书籍id 书名 用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean publishBooks(Books books, Integer userId) {
        // 查询作者id 根据用户id查询当前用户的作者身份数据
        Writer writer = writerMapper.selectByUserId(userId);
        books.setWriterId(writer.getId());

        //被替换的连载书籍必须完结
        Integer continuedBookId = writer.getContinuedBookId();
        if(continuedBookId != null){
            Books books1 = booksMapper.selectById(continuedBookId);
            if (books1 != null &&  books1.getContinuedState().equals(ContinuedState.SERIALIZE)){
                throw new UserActionException(ExceptionCodeMessage.SERIAL_ONLY);
            }
        }


        // 保证一个作者不出现两本书同名
        if (booksMapper.selectBookNameAmount(userId, books.getBookName()) != 0) {
            throw new UserActionException(ExceptionCodeMessage.REPETITION_BOOK);
        }

        try {
            //TODO:存储介质
            String url = RESOURCE_PATH + "BookWarehouse\\";
            File file = new File(url, books.getWriterId() + "\\" + books.getBookName() + "\\DeletedChapter");
            String urls = url + books.getWriterId() + "\\" + books.getBookName();

            books.setBookUrl(urls);//设置书籍url
            books.setChapter(0);//设置章节数量 0
            books.setWordCount(0);//设置总字数 0
            books.setCreateTime(new Date());//书籍创建时间

            if (file.mkdirs()) {
                // 成功创建目录，将数据存入数据库
                booksMapper.insert(books);
                //修改作者信息
                Integer booksCount = writer.getBooksCount();
                if (booksCount == null) {
                    booksCount = 0;
                }
                writer.setBooksCount(booksCount+1);
                writer.setContinuedBookId(books.getId());
                writerMapper.updateById(writer);

                return true;
            }
        } finally {
            //TODO:数据库插入失败，删除书籍磁盘位置

        }

        // 目录创建失败(目录已存在/书名重复)
        // return false;
        throw new UserActionException(ExceptionCodeMessage.REPETITION_BOOK);
    }

    /**
     * 逻辑删除一本已发布发布的书
     */
    @Override
    public boolean deleteBooks(Books books) {
        return unavailableBooks(books) && (booksMapper.updateBookDeleteState(books.getId()) == 1);
    }

    /**
     * 下架一本已上架的书
     */
    @Override
    public boolean unavailableBooks(Books books) {
        return booksMapper.updateBookSaleState(books.getId()) == 1;
    }

    /**
     * 修改一本书的信息
     */
    @Override
    public boolean reviseBooks(Books books) {
        //==0表示在未删除的书籍数据中找到0条
        if (booksMapper.selectAllByQuantity(books.getId()) == 0) {
            return false;
        }
        String url = booksMapper.selectBookIDqueryURL(books.getId());
        books.setBookUrl(url);
        return booksMapper.updateById(books) == 1;
    }

    /**
     * 查询这个作者发布的所有书籍 name & url（不包括以已删除的） state==true已上架/false未上架
     */
    @Override
    public List<Books> queryBooks(Writer writer, Boolean state) {
        //查询作者是否存在
        if (writerMapper.selectAllByIdInteger(writer.getId()) == 0) {
            return null;
        }
        List<Books> list;
        if (state) {
            list = booksMapper.selectNotDeletedBookNameURL(writer, 1);
        } else {
            list = booksMapper.selectNotDeletedBookNameURL(writer, 0);
        }
        //这些Books对象只有id,name,url有数据
        return list;
    }

    /**
     * 查询这个作者发布的所有已删除书籍
     */
    @Override
    public List<Books> queryBooksDeleted(Writer writer) {
        if (writerMapper.selectAllByIdInteger(writer.getId()) == 0) {
            return null;
        }
        return booksMapper.selectDeletedBookNameURL(writer);
    }
}
